package com.hod.client.lodging;

import java.util.Date;

import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.FieldSet;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.NumberField;
import com.gwtext.client.widgets.form.TextField;
import com.hod.client.HOD;
import com.hod.client.backend.orm.client.GearsDataObject;
import com.hod.client.backend.orm.client.GearsDataStore;
import com.hod.client.bed.Bed;
import com.hod.client.bed.BedRecordset;
import com.hod.client.client.Client;
import com.hod.client.client.ClientRecordset;
import com.hod.client.frontend.HODForm;
import com.hod.client.reserves.ReservationRecordset;
import com.hod.client.room.Room;
import com.hod.client.room.RoomRecordset;

public class LodgingFormPanel extends HODForm {
	
    protected final TextField txtIdLodging = new TextField("idLodging", "idLodging", 150);
	protected final DateField txtCheckIn = new DateField("checkIn", "checkIn", 150);
	protected final DateField txtCheckOut = new DateField("checkOut", "checkOut", 150);
	protected final NumberField txtTotal = new NumberField("total", "total", 150);
    protected final ListBox txtIdClient = new ListBox();
    protected final ListBox txtIdRoom = new ListBox();
    protected final ListBox txtIdBed = new ListBox();
    protected final ListBox txtIdReservation = new ListBox();
    protected Room[] roomArray;
    
    protected Integer idReservation = 0;
	private Integer idClient = 0;
	private Integer idRoom = 0;
	private Integer idBed = 0;


	public LodgingFormPanel(GearsDataStore ds) {
		super(ds);
		roomArray = RoomRecordset.getRooms();
		add(createFieldSet());        
        createButtons();
		// TODO Auto-generated constructor stub
	}
	
	public void setIdClient(Integer idClient){
		this.idClient = idClient;
	}
	
	public void setIdReservation(Integer idReservation){
		this.idReservation = idReservation;
	}
	
	public void setRooms(Room[] room) {
		// TODO Auto-generated method stub
		this.roomArray = room;
		
	}

	@Override
	protected void createButtons() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		ButtonListenerAdapter savelistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		Lodging o = null;
            		if (txtIdLodging.getText()==""){
            			o = new Lodging();
            			o.setIdLodging(null);
            		}else{
            			o = (Lodging) ds.findById(Integer.valueOf(txtIdLodging.getText()));
            		}
                    o.setIdClient(Integer.valueOf(txtIdClient.getValue(txtIdClient.getSelectedIndex())));
                    o.setIdRoom(Integer.valueOf(txtIdRoom.getValue(txtIdRoom.getSelectedIndex())));
                    o.setIdBed(Integer.valueOf(txtIdBed.getValue(txtIdBed.getSelectedIndex())));
                    if (txtCheckOut.getValue().after(new Date())) //queda bloqueada solamente si la fecha es posterior a hoy
                       RoomRecordset.setRoomState(txtIdRoom.getValue(txtIdRoom.getSelectedIndex()), "OCCUPIED"); //seteo la habitacion como ocupada
                    else
                    	RoomRecordset.setRoomState(txtIdRoom.getValue(txtIdRoom.getSelectedIndex()), "FREE"); //seteo la habitacion como libre si la fecha de checkout es anterior a hoy
                    if (idReservation!=0){
                    	ReservationRecordset.setStateFinished(idReservation);
                    }
                    o.setIdReservation(idReservation);
                    o.setCheckIn(txtCheckIn.getValue());
                    o.setCheckOut(txtCheckOut.getValue());
                    o.setTotal(Double.valueOf(txtTotal.getText()));
                    ds.save(o);
                    HOD.reload();
				} 
            	catch (Exception e1) {
					// TODO Auto-generated catch block
            		com.google.gwt.user.client.Window.alert(e1.getMessage());
				}
            }
        };
        ButtonListenerAdapter deletelistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		ds.delete((Lodging) ds.findById(new Integer(txtIdLodging.getText())));
            		HOD.reload();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					com.google.gwt.user.client.Window.alert(e1.getMessage());
				}
            }
        };
        ButtonListenerAdapter createlistener = new ButtonListenerAdapter() {
            public void onClick(Button button, EventObject e) {
            	try {
            		getForm().reset();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					com.google.gwt.user.client.Window.alert(e1.getMessage());
				}
            }
        };
        	           
        
        Button save = new Button("Save", savelistener);
        Button delete = new Button("Delete", deletelistener);
		Button newRecord = new Button("New", createlistener);
        Button cancel = new Button("Cancel");

        addButton(save);
        addButton(delete);
        addButton(cancel);
        addButton(newRecord);
	}

	@Override
	protected FieldSet createFieldSet() {
		// TODO Auto-generated method stub

		txtIdClient.clear();
		txtIdRoom.clear();
		
        for(Client c: ClientRecordset.getClients()){
        	   txtIdClient.addItem(c.getName(),String.valueOf(c.getIdClient()));
        	   if ((idClient!=0) && (idClient.equals(c.getIdClient()))){
        		   txtIdClient.setItemSelected(txtIdClient.getItemCount()-1, true);
        	   }
        }

        for(Room c: roomArray){
     	   txtIdRoom.addItem(c.getNumber(),String.valueOf(c.getIdRoom()));
     	   if ((idRoom!=0) && (idRoom .equals(c.getIdRoom()))){
     		   txtIdRoom.setItemSelected(txtIdRoom.getItemCount()-1, true);
     	   }
        }
        
        for(Bed c: BedRecordset.getBed()){
      	   txtIdBed.addItem(c.getNumber()+"",String.valueOf(c.getIdBed()));
      	   if ((idBed !=0) && (idBed.equals(c.getIdBed()))){
      		   txtIdBed.setItemSelected(txtIdBed.getItemCount()-1, true);
      	   }
        }
        

		FieldSet fieldSet = new FieldSet();
        fieldSet.setLabelWidth(80);
        fieldSet.setTitle("Lodging Details");
        fieldSet.setAutoHeight(true);
        fieldSet.setBorder(false);

        //the field names must match the data field values from the Store
        fieldSet.add(txtIdLodging);
        fieldSet.add(txtCheckIn);
        fieldSet.add(txtCheckOut);
        fieldSet.add(txtTotal);
        fieldSet.add(new Label("Cliente"));
        fieldSet.add(txtIdClient);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Habitacion"));
        fieldSet.add(txtIdRoom);
        fieldSet.add(new HTML("<BR/>"));
        fieldSet.add(new Label("Cama"));
        fieldSet.add(txtIdBed);
        
        txtIdLodging.setReadOnly(true);    
        txtIdLodging.setVisible(false);
        txtIdLodging.setHideLabel(true);
        txtCheckIn.setAllowBlank(false);
        txtCheckOut.setAllowBlank(true);
        txtTotal.setAllowDecimals(true);
        txtTotal.setAllowNegative(true);
        txtCheckIn.setValue(new Date());
        
        
        //fieldSet.add(formTabs());
        return fieldSet;
	}

	@Override
	public void updateDataControls(Record record) {
		// TODO Auto-generated method stub
		getForm().loadRecord(record);
        idClient = record.getAsInteger("idClient");
        idRoom = record.getAsInteger("idRoom");
        
        for (int i=0;i<txtIdRoom.getItemCount();i++)
           if (Integer.valueOf(txtIdRoom.getValue(i))==record.getAsInteger("idRoom"))
     	       txtIdRoom.setItemSelected(i, true);
        
        for (int i=0;i<txtIdClient.getItemCount();i++)
            if (Integer.valueOf(txtIdClient.getValue(i))==record.getAsInteger("idClient"))
            	txtIdClient.setItemSelected(i, true);
        
        for (int i=0;i<txtIdBed.getItemCount();i++)
            if (Integer.valueOf(txtIdBed.getValue(i))==record.getAsInteger("idBed"))
            	txtIdBed.setItemSelected(i, true);

	}

	@Override
	public void setObject(GearsDataObject object) {
		// TODO Auto-generated method stub
		
	}

}
